package com.example.demo.service;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;


/**
 * @author 谢辉
 * @Classname PdfService
 * @Description TODO
 * @Date 2020/12/4 15:58
 */
@Service
public class PdfService {

    public void getPDF(String filepath, String filename, HttpServletResponse response) throws Exception{
        if(filepath!=null){
            //设置反应类型
            try {
                java.io.File file=new java.io.File(filepath);
                if(!file.exists()){
                    return;
                }

                //利用PDF.js读取文件涉及到跨域访问，故添加权限
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setContentType("application/octet-stream;charset=utf-8");
                response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //读取指定路径下面的文件
            InputStream in = new FileInputStream(filepath);
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //创建存放文件内容的数组
            byte[] buff =new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while((n=in.read(buff))!=-1){
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff,0,n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();
            in.close();
        }
    }



    public void getPDF(String urlfilepath, HttpServletResponse response) throws Exception{

        if(urlfilepath!=null){
            String filename = urlfilepath.substring(urlfilepath.lastIndexOf("/")+1);
            System.out.println("filename:" + filename);
            //利用PDF.js读取文件涉及到跨域访问，故添加权限
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            //读取指定路径下面的文件
            URL url = new URL(urlfilepath);
            InputStream in = url.openStream();
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //创建存放文件内容的数组
            byte[] buff =new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while((n=in.read(buff))!=-1){
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff,0,n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();
            in.close();
        }
    }
}
